<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
                        v-model="queryParams.orderTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100px">
          <el-option
              v-for="dict in assign_order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="assignOrdersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="取餐码" align="center">
        <template #default="scope">
          {{ scope.row.orderbasic?.pickupNumber || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="收获地址" align="center" width="250">
        <template #default="scope">
          {{ scope.row.orderbasic?.address || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="配送距离(千米)" align="center" prop="deliveryDistanceKm" />
      <el-table-column label="下单时间" align="center" prop="orderbasic.orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderbasic?.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="assign_order_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-dropdown>
            <el-button type="text" size="small" class="dropdown-trigger">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>

              <!-- 下拉菜单中的分配选项 -->
              <el-dropdown-menu>
                <el-dropdown-item
                    @click="handleAssign(scope.row)"
                    v-hasPermi="['system:assignOrders:assign']"
                >
                  <el-icon><User /></el-icon>指派订单
                </el-dropdown-item>
                <el-dropdown-item
                    @click="handleDetail(scope.row)"
                    v-hasPermi="['system:assignOrders:detail']"
                >
                  <el-icon><View /></el-icon>查看详情
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="assignOrdersRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配骑手弹窗 -->
    <AssignRider
        :visible="showAssignDialog"
        @update:visible="val => showAssignDialog = val"
        :order-id="currentOrderId"
        @assign="handleAssignRider"
    />
  </div>
</template>

<script setup name="AssignOrders">
import { listAssignOrders } from "@/api/system/assignOrders.js"
import AssignRider from './assignRider.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const { proxy } = getCurrentInstance()
const { assign_order_type } = proxy.useDict('assign_order_type')

const assignOrdersList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const showAssignDialog = ref(false)
const detailVisible = ref(false)
const detailTitle = ref('订单详情')
const currentOrderId = ref(null)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    orderTime: null,
    status: null,  // 这里确保初始值为null而不是0
    id: null
  }
})


const { queryParams } = toRefs(data)

/** 查询订单列表 */
function getList() {
  loading.value = true
  listAssignOrders(queryParams.value).then(response => {
    assignOrdersList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
}

// 处理分配点击
const handleAssign = (row) => {
  currentOrderId.value = row.id
  showAssignDialog.value = true
}

// 处理分配骑手
const handleAssignRider = async ({ id, riderInfo }) => {
  try {
    // 可以在这里添加额外的处理逻辑
    proxy.$modal.msgSuccess(`订单 ${id} 已成功分配给骑手 ${riderInfo.name}`)
    getList() // 刷新列表
  } catch (error) {
    proxy.$modal.msgError('分配失败: ' + (error.message || error))
  } finally {
    showAssignDialog.value = false
  }
}
//只能选择一名骑手

/** 导出按钮操作 */
function handleExport() {
  proxy.$modal.confirm('确认导出所有订单数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return exportAssignOrders(queryParams.value)
  }).then(response => {
    proxy.download(response.msg)
  }).catch(() => {})
}

onMounted(() => {
  getList()
})
</script>


<style scoped>
/* 三点触发按钮样式 */
.dropdown-trigger {
  color: #606266;
  font-size: 16px;
  padding: 0 8px;
}

.dropdown-trigger:hover {
  color: #409EFF;
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 下拉菜单项样式 */
.el-dropdown-menu__item {
  font-size: 14px;
  line-height: 28px;
  padding: 0 16px;
}

.el-dropdown-menu__item .el-icon {
  margin-right: 8px;
  font-size: 14px;
}

</style>